package com.boxedinsoftware.betamax.dial;



import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.widget.Toast;

 public class OutgoingCallBackReceiver extends Activity {

		protected SharedPreferences preferences;
		protected String number;
		protected static String usernameString;
		protected static String passwordString;
		protected static String providerString;
		protected static String sourceNumberString;
		protected boolean callBackDebugBoolean = false;

	 
	 @Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			
			
			preferences = PreferenceManager.getDefaultSharedPreferences(this);
			String full_number = this.getIntent().getDataString();
			
			number = full_number.substring(full_number.indexOf(":") + 1, full_number.length());
			number = number.replaceAll("%2B", "+");
			
			if(number.startsWith("+"))
			{
				
				usernameString = preferences.getString("username", "none");
				passwordString = preferences.getString("psswd", "none");
				providerString = preferences.getString("betamaxProvider", "0");
				sourceNumberString = preferences.getString("ownNumber", "");
				sourceNumberString = sourceNumberString.trim();
			  
			   
			   
           	
           		
           		number = number.replaceAll( "-", "" );
                number = number.replace(")", "");
                number = number.replace("(", "");
                number = number.replaceAll(" ", "");
                number = number.replaceAll("[a-z,A-Z]", "");
                number = number.replace("+", "0");
                number = "0" + number;
                number = number.trim();
           	
                
            	if(usernameString.equalsIgnoreCase("none") ||passwordString.equalsIgnoreCase("none") || providerString.equalsIgnoreCase("0"))
            	{
            	Toast.makeText(this, "Unable to make CallBack. Please set up your account.", Toast.LENGTH_LONG).show();
            	Intent i = new Intent(OutgoingCallBackReceiver.this, dialNowPrefs.class);
    			startActivityForResult(i, 103);
            	finish();
            	}
            	else if(!sourceNumberString.startsWith("+"))
    			{
    				
    				Toast.makeText(this, "Unable to make CallBack. Please update your own number in International format", Toast.LENGTH_LONG).show();
    				Intent i = new Intent(OutgoingCallBackReceiver.this, dialNowPrefs.class);
        			startActivityForResult(i, 103);
        			finish();
    			}
            	else
            		new callBack().execute("");	
            	
            	
	      	   
	      	   
			
			}
			else
			{
				
				
				Toast.makeText(this, "Please use international format. Eg: +16476806419924", Toast.LENGTH_LONG).show();
				finish();
				
				
			}
			
			
			
			
			
			
	 }
	 
	 public class callBack extends AsyncTask<String, Void, String> {
	    	final ProgressDialog progress = ProgressDialog.show(OutgoingCallBackReceiver.this,    
	                "Requesting CallBack ... ", "Please wait ... You will receive a Private Call after this dialog closes.", true);
	    	
	    	
	    	@Override
	    	protected String doInBackground(String... params) {
	    		try{
	        		
	        		
					String usernameString = preferences.getString("username", "none");
					String passwordString = preferences.getString("psswd", "none");
					String providerString = preferences.getString("betamaxProvider", "0");
					String sourceNumberString = preferences.getString("ownNumber", "");
					callBackDebugBoolean = preferences.getBoolean("callbackDebug", false);
					
					if(sourceNumberString.equalsIgnoreCase(""))
					{
						TelephonyManager tMgr =(TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
						sourceNumberString= tMgr.getLine1Number();
						
					}
					
					if(sourceNumberString.startsWith("+"))
					{
						
						sourceNumberString = sourceNumberString.replace('+', '0');
						sourceNumberString = "0" + sourceNumberString;
						
					}
					
					//Log.e("providerString", providerString);
					String actualProvider = dialNow.PROVIDERS[new Integer(Integer.parseInt(providerString))];
					//Log.e("actualProvider", actualProvider);
					if(!providerString.equalsIgnoreCase("0"))
					{
				    HttpClient httpclient = new DefaultHttpClient();  
			        HttpGet httpget = new HttpGet("http://www.aldeaglobal.net/callserver/call.php?provider="+actualProvider+"&us="+usernameString+"&ps="+passwordString+"&tela="+sourceNumberString+"&telb="+number);
			       
		            // Add your data  
		            
		      
		            // Execute HTTP Post Request  
		            HttpResponse response = httpclient.execute(httpget);  
		            
		            byte buffer[] = new byte[1024] ;
					InputStream is = response.getEntity().getContent() ;
					int numBytes = is.read(buffer) ;
					is.close();
					
					 String entityContents = new String(buffer,0,numBytes) ;
				    
						

						
			            
					 return entityContents;   
					}
					
					
					return "none";
			            
			           
			            
		            
		            
		            
		            
		              
		        } catch (ClientProtocolException e) {  
		        	return e.getMessage();
		        } catch (IOException e) {  
		        	return e.getMessage(); 
		        }
		        
		       
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	    	 */
	    	@Override
	    	protected void onPostExecute(String result) {
	    		
	            progress.dismiss();
	            if(callBackDebugBoolean == true)
	            	displayDebug(result);
	            else
	            	OutgoingCallBackReceiver.this.finish();
	    		
	    		super.onPostExecute(result);
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onPreExecute()
	    	 */
	    	@Override
	    	protected void onPreExecute() {
	    		// TODO Auto-generated method stub
	    		super.onPreExecute();
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	    	 */
	    	@Override
	    	protected void onProgressUpdate(Void... values) {
	    		// TODO Auto-generated method stub
	    		super.onProgressUpdate(values);
	    	}

	    }
	 
	 public void displayDebug(final String message)
	    {
	    	ComponentName comp = new ComponentName(OutgoingCallBackReceiver.this, dialNow.class);
	        PackageInfo pinfo = null;
			try {
				pinfo = OutgoingCallBackReceiver.this.getPackageManager().getPackageInfo(comp.getPackageName(), 0);
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	final String firmwareVersion = Build.VERSION.RELEASE;
	    	final String model = Build.MODEL;
	    	final String display = Build.DISPLAY;
	    	final String appVersion = pinfo.versionName;
	    	final int appCode = pinfo.versionCode;
	    	providerString = preferences.getString("betamaxProvider", "0");
	    	final String actualProvider = dialNow.PROVIDERS[new Integer(Integer.parseInt(providerString))];
	    	
	    	
	    	
	    	
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	builder.setTitle("Debug Dialog")
	    	       .setMessage("Firmware : " + firmwareVersion + "\n" +
	    	    		   	   "Phone Model : " + model + "\n" +
	    	    		   	   "ROM : " + display + "\n" +
	    	    		   	   "App Version : " + appVersion + "\n" +
	    	    		   	   "App Code : " + appCode + "\n" +
	    	    		   	   "BetaMax Provider : " + actualProvider + "\n\n\n" + 
	    	    		   	   "DEBUG MESSAGE STARTS HERE\n" +
	    	    		   	   "-------------------------------------------\n" + 
	    	    		   	   message+
	    	    		   	   "\n-------------------------------------------")
	    	       .setCancelable(false)
	    	       .setNegativeButton("OK", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	        	   OutgoingCallBackReceiver.this.finish();
	    	                dialog.cancel();
	    	           }
	    	       })
	    	       .setPositiveButton("Send To Dev", new DialogInterface.OnClickListener() {
	    	           public void onClick(DialogInterface dialog, int id) {
	    	        	   final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
	                       
	                       emailIntent.setType("plain/text");
	                  
	                       emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "support@boxedinsoftware.com"});
	                
	                       emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "[DEBUG BetaMax Dialer Pro v" + appVersion +"]");
	                
	                       emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
	                    		   "\n\n\n-------------------------------------------\n" +
	                       		   "Firmware : " + firmwareVersion + "\n" +
	        	    		   	   "Phone Model : " + model + "\n" +
	        	    		   	   "ROM : " + display + "\n" +
	        	    		   	   "App Version : " + appVersion + "\n" +
	        	    		   	   "App Code : " + appCode + "\n" + 
	        	    		   	   "BetaMax Provider : " + actualProvider + "\n\n\n" +
	        	    		   	   "DEBUG MESSAGE STARTS HERE\n" +
	        	    		   	   "-------------------------------------------\n" + 
	        	    		   	   message+
	        	    		   	   "\n-------------------------------------------");
	        
	                       OutgoingCallBackReceiver.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
	                       OutgoingCallBackReceiver.this.finish();
	    	           }
	    	       });
	    	AlertDialog alert = builder.create();
	    	alert.show();
	        
	        
	        
	    }

 }